import axios, { AxiosRequestConfig } from "axios";
import { useRef, useState } from "react";
function useRequest<T>(url: string, config: AxiosRequestConfig) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const controllerRef = useRef(new AbortController());

  const cancelRequest = () => {
    controllerRef.current.abort();
  };
  const fetchData = async () => {
    // 清除数据
    setData(null);
    setError(null);
    setLoading(false);
    // try {
    //   setLoading(true);
    //   const response = await axios.request<T>({
    //     url,
    //     ...config,
    //     signal: controllerRef.current.signal,
    //   });
    //   setData(response.data);
    //   console.log("🚀 ~ fetchData ~ response:", response);
    // } catch (error: any) {
    //   setError(error || "An error occurred");
    // } finally {
    //   setLoading(false);
    // }
    return axios
      .request<T>({
        url,
        ...config,
        signal: controllerRef.current.signal,
      })
      .then((res) => {
        setData(res.data);
        return res.data;
      })
      .catch((err) => {
        setError(err || "An error occurred");
        throw new Error(err);
      })
      .finally(() => {});
  };

  return { loading, error, fetchData, cancelRequest };
}

export default useRequest;
